package com.quanyan.travel.service.impl;

import com.google.gson.Gson;
import com.quanyan.api.APIResponse;
import com.quanyan.comment.constants.UserCenterConstants;
import com.quanyan.comment.reqeust.ReqCommentQuery;
import com.quanyan.comment.reqeust.ReqUserCollect;
import com.quanyan.comment.reqeust.ReqUserCollectQuery;
import com.quanyan.comment.response.RespComment;
import com.quanyan.comment.serviceFacade.CommentServiceFacade;
import com.quanyan.comment.serviceFacade.UserCollectServiceFacade;
import com.quanyan.common.Plugin.PageObj;
import com.quanyan.travel.api.req.ReqActivity;
import com.quanyan.travel.api.resp.*;
import com.quanyan.travel.biz.BizTravelOrderService;
import com.quanyan.travel.constants.OutdoorConstants;
import com.quanyan.travel.entity.*;
import com.quanyan.travel.entity.vo.ActivityParameter;
import com.quanyan.travel.entity.vo.Master;
import com.quanyan.travel.entity.vo.MultiMedia;
import com.quanyan.travel.mapper.TbOutdoorActivityDescMapper;
import com.quanyan.travel.mapper.TbOutdoorActivityMapper;
import com.quanyan.travel.mapper.TbOutdoorProductMapper;
import com.quanyan.travel.service.TravelDetailService;
import com.quanyan.user.response.RespUserInfoBase;
import com.quanyan.user.response.RespUserInfoDetail;
import com.quanyan.user.serviceFacade.UserServiceFacade;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 *@author dongshenglin
 * @date 2016/5/26  20:45
 */

@Service("travelDetailService")
public class TravelDetailServiceImpl implements TravelDetailService {


    @Autowired
    private TbOutdoorActivityMapper tbOutdoorActivityMapper;

    @Autowired
    private TbOutdoorActivityDescMapper tbOutdoorActivityDescMapper;

    @Autowired
    private TbOutdoorProductMapper tbOutdoorProductMapper;

    @Autowired
    private UserCollectServiceFacade userCollectServiceFacade;

    @Autowired
    private CommentServiceFacade commentServiceFacade;

    @Autowired
    private BizTravelOrderService bizTravelOrderService;

    @Autowired
    private UserServiceFacade userServiceFacade;

    private static Logger logger = LoggerFactory.getLogger(TravelDetailServiceImpl.class);

    /**
     * 价格日历
     * @param uid
     * @param activityId
     * @param request
     * @return
     */

    @Override
    public APIResponse<RespAppActivityDetail> getPriceCalendar(Integer uid,Integer activityId,HttpServletRequest request) {
        if (null == activityId){
            return APIResponse.returnFail("活动id为空");
        }
        TbOutdoorProductExample tbOutdoorProductExample = new TbOutdoorProductExample();
        TbOutdoorProductExample.Criteria criteria = tbOutdoorProductExample.createCriteria();
        criteria.andActivityIdEqualTo(activityId);
        criteria.andIsDeleteEqualTo(OutdoorConstants.DEFAULT_STATUS_byte_NO);
        tbOutdoorProductExample.setOrderByClause("start_time ASC");
        List<TbOutdoorProduct> tbOutdoorProductList = tbOutdoorProductMapper.selectByExample(tbOutdoorProductExample);
        List<RespPriceCalendar> respRriceCalendars = new ArrayList<>();
        if (tbOutdoorProductList.size() >0){
            for (TbOutdoorProduct productroduct : tbOutdoorProductList){
                RespPriceCalendar priceCalendar = new RespPriceCalendar();
                BeanUtils.copyProperties(productroduct,priceCalendar);
                priceCalendar.setProductId(productroduct.getId());
                respRriceCalendars.add(priceCalendar);
            }
        }
        boolean isCollected = false;
        if (uid !=null && uid != 0) {
            isCollected = isFavorite(uid,activityId);
        }
        RespAppActivityDetail detail = new RespAppActivityDetail();
        detail.setActivityId(activityId);
        detail.setIsFavorite(isCollected);
        detail.setCalendarList(respRriceCalendars);

        //判断是否为季度活动
        detail.setIsQuanter(this.isQuarter(activityId));
        RespShareActivity shareActivity = new RespShareActivity();

        //目的地
        TbOutdoorActivityDestination destination = bizTravelOrderService.queryTbOutdoorActivityDestinationByActivityId(activityId);
        if (null != destination){
            TbOutdoorDestination outdoorDestination=  bizTravelOrderService.queryTbOutdoorDestinationById(destination.getDestinationId());
            if (null != outdoorDestination){
                detail.setDestination_lng(outdoorDestination.getLng());
                detail.setDestination_lat(outdoorDestination.getLat());
                detail.setDestination(outdoorDestination.getAddress());
            }
        }
        //活动分享信息
        TbOutdoorActivity vOutdoorActivityPreview = tbOutdoorActivityMapper.selectByPrimaryKey(activityId);
        detail.setLat(vOutdoorActivityPreview.getLat());
        detail.setLng(vOutdoorActivityPreview.getLng());
        detail.setAddress(vOutdoorActivityPreview.getAddress());
        //活动状态
        Byte status = 1;
        if (null != vOutdoorActivityPreview) {
            detail.setPrice(vOutdoorActivityPreview.getPrice());
            detail.setDisplayPrice(vOutdoorActivityPreview.getDisplayPrice());
            detail.setStatus(vOutdoorActivityPreview.getIsDelete());
            shareActivity.setTitle(vOutdoorActivityPreview.getName());
            shareActivity.setContent(vOutdoorActivityPreview.getExtendName());
            Gson gson = new Gson();
            MultiMedia multiMedia = gson.fromJson(vOutdoorActivityPreview.getMultiMedia(), MultiMedia.class);
            if (multiMedia.getType() == 0) {
                shareActivity.setImageUrl(multiMedia.getImage().getImageUrl());
            } else if (multiMedia.getType() == 1) {
                shareActivity.setImageUrl(multiMedia.getVideo().getImageUrl());
            }
            shareActivity.setShareUrl(request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() +
                    OutdoorConstants.ACTIVITY_SHARE_URL + "?activityId=" + activityId + "&from=share");
            detail.setShareActivity(shareActivity);
        }
        return APIResponse.returnSuccess(detail);
    }

    /**
     * 获取单场活动详情
     * @param activityId
     * @return
     */
    @Override
    public RespOutdoorActivityDetail getTravelOverviewSingle(Integer activityId) {
        TbOutdoorActivity vOutdoorActivityPreview = tbOutdoorActivityMapper.selectByPrimaryKey(activityId);
        if (null == vOutdoorActivityPreview) {
            return null;
        }
        RespOutdoorActivityDetail respOutdoorActivityDetail = this.structureOutdoorActivityOverView(vOutdoorActivityPreview);
        respOutdoorActivityDetail.setActivityId(activityId);
        respOutdoorActivityDetail.setActivityType(OutdoorConstants.THEME_ACTIVITY_NO.intValue());
        return respOutdoorActivityDetail;
    }


    private RespOutdoorActivityDetail structureOutdoorActivityOverView(TbOutdoorActivity tbOutdoorActivity){
        RespOutdoorActivityDetail respOutdoorActivityDetail = new RespOutdoorActivityDetail();
        Integer activityId = tbOutdoorActivity.getId();
        respOutdoorActivityDetail.setActivityName(tbOutdoorActivity.getName());

        Gson gson = new Gson();
        MultiMedia multiMedia = gson.fromJson(tbOutdoorActivity.getMultiMedia(), MultiMedia.class);
        respOutdoorActivityDetail.setMultiMedia(multiMedia);

        ActivityParameter parameter = gson.fromJson(tbOutdoorActivity.getParameter(),ActivityParameter.class);
        respOutdoorActivityDetail.setParameter(parameter);

        respOutdoorActivityDetail.setLat(tbOutdoorActivity.getLat());
        respOutdoorActivityDetail.setLng(tbOutdoorActivity.getLng());
        respOutdoorActivityDetail.setAddress(tbOutdoorActivity.getAddress());
        respOutdoorActivityDetail.setPrice(tbOutdoorActivity.getPrice());
        respOutdoorActivityDetail.setDisplayPrice(tbOutdoorActivity.getDisplayPrice());

        /**
         * 活动是否未删除，删除或下架为false
         */
        respOutdoorActivityDetail.setIsDelete(tbOutdoorActivity.getIsDelete() == OutdoorConstants.IS_NOT_DELETE ? true :false);

        //目的地
        TbOutdoorActivityDestination destination = bizTravelOrderService.queryTbOutdoorActivityDestinationByActivityId(activityId);
        if (null != destination){
            TbOutdoorDestination outdoorDestination=  bizTravelOrderService.queryTbOutdoorDestinationById(destination.getDestinationId());
            if (null != outdoorDestination){
                respOutdoorActivityDetail.setDestination(outdoorDestination.getAddress());
                respOutdoorActivityDetail.setDestination_lng(outdoorDestination.getLng());
                respOutdoorActivityDetail.setDestination_lat(outdoorDestination.getLat());
            }
        }

        //查询活动持续时间和最少最多报名人数
        //Integer minNUm = 1;
        //Integer maxNum = 1;
        TbOutdoorProductExample tbOutdoorProductExample = new TbOutdoorProductExample();
        TbOutdoorProductExample.Criteria criteria = tbOutdoorProductExample.createCriteria();
        criteria.andActivityIdEqualTo(activityId);
        criteria.andIsDeleteEqualTo(OutdoorConstants.DEFAULT_STATUS_byte_NO);
        criteria.andSignStartTimeGreaterThan(new Date());
        tbOutdoorProductExample.setOrderByClause("start_time ASC");
        List<TbOutdoorProduct> tbOutdoorProductList = tbOutdoorProductMapper.selectByExample(tbOutdoorProductExample);
        Date startDate = new Date();
        if (tbOutdoorProductList.size() > 0){
            startDate = tbOutdoorProductList.get(0).getStartTime();
        }
        respOutdoorActivityDetail.setStartTime(startDate);
        respOutdoorActivityDetail.setLimitNum(tbOutdoorActivity.getMinNum());
        respOutdoorActivityDetail.setMaxNum(tbOutdoorActivity.getLimitNum());
        respOutdoorActivityDetail.setActivityTime(tbOutdoorActivity.getActivityTime());

        //活动介绍和注意事项
        TbOutdoorActivityDescExample tbOutdoorActivityDescExample = new TbOutdoorActivityDescExample();
        TbOutdoorActivityDescExample.Criteria criteria1 = tbOutdoorActivityDescExample.createCriteria();
        criteria1.andOutdoorActivityIdEqualTo(activityId);
        List<TbOutdoorActivityDesc> tbOutdoorActivityDescList = tbOutdoorActivityDescMapper.selectByExample(tbOutdoorActivityDescExample);
        if (tbOutdoorActivityDescList.size() == 1){
            TbOutdoorActivityDesc tbOutdoorActivityDesc = tbOutdoorActivityDescList.get(0);
            respOutdoorActivityDetail.setActivityIntroduce(tbOutdoorActivityDesc.getBodyDesc());
            respOutdoorActivityDetail.setActivityNote(tbOutdoorActivityDesc.getAttentionDesc());
        }

        //执行领队列表
        List<Integer> activityIds = new ArrayList<>();
        activityIds.add(activityId);
        List<Master> masterList = bizTravelOrderService.queryOutdoorMaster(activityIds);
        respOutdoorActivityDetail.setMasterList(masterList);

        //收藏用户列表
        ReqActivity collectUserRequest = new ReqActivity();
        collectUserRequest.setPageNo(OutdoorConstants.FIRST_PAGE);
        collectUserRequest.setPageSize(OutdoorConstants.COLLECTUSER_NUM);
        collectUserRequest.setSystemId(UserCenterConstants.SystemCode.SYSTEM_OUTDOOR);
        collectUserRequest.setBusinessId(UserCenterConstants.BusinessCode.BUSINESS_OUTDOOR_CM);
        collectUserRequest.setActivityId(activityId);
        PageObj<List<RespActivityUser>> pageCollectUsers = getCollectionUserList(collectUserRequest);
        Integer userNum = 0;
        if (null != pageCollectUsers){
            List<RespActivityUser> userList = pageCollectUsers.getItems();
            respOutdoorActivityDetail.setUserList(userList);
            userNum = pageCollectUsers.getTotal();
        }
        respOutdoorActivityDetail.setUserNum(userNum);

        //评论列表
        ReqActivity commentRequest = new ReqActivity();
        commentRequest.setPageNo(OutdoorConstants.FIRST_PAGE);
        commentRequest.setPageSize(OutdoorConstants.COMMENT_NUM);
        commentRequest.setActivityId(activityId);
        PageObj<List<RespActivityComment>> pageComments = getActivityCommentList(commentRequest);
        List<RespActivityComment> commentList = new ArrayList<>();
        if(null != pageComments){
            commentList = pageComments.getItems();
            respOutdoorActivityDetail.setCommentNum(pageComments.getTotal());
        }
        respOutdoorActivityDetail.setCommentList(commentList);
        return respOutdoorActivityDetail;
    }

    /**
     * 活动收藏及取消
     * @param uid
     * @param activityId
     * @param status
     * @return
     */
    @Override
    public boolean changeFavorite(Integer uid,Integer activityId, Integer status) {
        boolean result = false;
        ReqUserCollect collect = new ReqUserCollect();
        collect.setSystemCode(UserCenterConstants.SystemCode.SYSTEM_OUTDOOR);
        collect.setBusinessCode(UserCenterConstants.BusinessCode.BUSINESS_OUTDOOR_CM);
        collect.setBusinessId(activityId);
        collect.setUserId(uid);
        collect.setStatus(status);
        try {
            if (status == 0){
                result =  userCollectServiceFacade.cancleUserCollect(collect).isRet();
            }else if(status == 1){
                result = userCollectServiceFacade.userCollect(collect).isRet();
            }
        }catch (Exception e){
            logger.error("用户收藏服务调不通!");
            result = false;
        }
        return result;
    }

    /**
     * 活动是否收藏
     * @param uid
     * @param activityId
     * @return
     */
    @Override
    public boolean isFavorite(Integer uid,Integer activityId) {
        ReqUserCollectQuery userCollectQuery = new ReqUserCollectQuery();
        userCollectQuery.setSystemCode(UserCenterConstants.SystemCode.SYSTEM_OUTDOOR);
        userCollectQuery.setBusinessCode(UserCenterConstants.BusinessCode.BUSINESS_OUTDOOR_CM);
        userCollectQuery.setBusinessId(activityId);
        userCollectQuery.setUserId(uid);
        Boolean isCollected = false;
        try {
            isCollected = !userCollectServiceFacade.isUserCollect(userCollectQuery).getData();
        }catch (Exception e){
            logger.error("用户收藏服务调不通!");
        }
        return isCollected;
    }

    /**
     * 获取收藏用户列表
     * @param request
     * @return
     */
    public PageObj<List<RespActivityUser>> getCollectionUserList(ReqActivity request) {

        PageObj<List<Integer>>  listPageObj = getUserIdPage(request);
        if (null == listPageObj){
            return null;
        }
        List<Integer> userIds =  listPageObj.getItems();
        List<RespActivityUser> users = getUsers(userIds);
        PageObj<List<RespActivityUser>> pageObj = new PageObj<>();
        pageObj.setTotal(listPageObj.getTotal());
        pageObj.setPageCount(listPageObj.getPageCount());
        pageObj.setPageNum(listPageObj.getPageNum());
        pageObj.setItems(users);
        return pageObj;
    }

    /**
     * 获取(所有)收藏用户列表
     * @param activityId
     * @return
     */
    @Override
    public APIResponse<PageObj<List<RespActivityUser>>> getPageCollectionUsers(Integer activityId) {
        ReqActivity collectUserRequest = new ReqActivity();
        collectUserRequest.setPageNo(OutdoorConstants.FIRST_PAGE);
        collectUserRequest.setPageSize(OutdoorConstants.MAX_COLLECTUSER_NUM);
        collectUserRequest.setActivityId(activityId);
        PageObj<List<RespActivityUser>> pageCollectUsers = getCollectionUserList(collectUserRequest);
        if (null == pageCollectUsers){
            return APIResponse.returnSuccess(new PageObj<List<RespActivityUser>>());
        }
        return APIResponse.returnSuccess(pageCollectUsers);
    }

    /**
     * 获取六个最新的收藏用户
     * @param activityId
     * @return
     */
    @Override
    public APIResponse<PageObj<List<RespActivityUser>>> getSixCollectUser(Integer activityId) {
        ReqActivity collectUserRequest = new ReqActivity();
        collectUserRequest.setPageNo(OutdoorConstants.DEFAULT_FIRST_PAGE);
        collectUserRequest.setPageSize(OutdoorConstants.SIX_COLLECTUSERS);
        collectUserRequest.setActivityId(activityId);
        PageObj<List<RespActivityUser>> pageCollectUsers = getCollectionUserList(collectUserRequest);
        if (null == pageCollectUsers){
            return APIResponse.returnSuccess(new PageObj<List<RespActivityUser>>());
        }
        return APIResponse.returnSuccess(pageCollectUsers);
    }

    @Override
    public boolean isQuarter(Integer activityId) {
        TbOutdoorActivity tbOutdoorActivity= tbOutdoorActivityMapper.selectByPrimaryKey(activityId);
        if (null != tbOutdoorActivity){
            Byte type = tbOutdoorActivity.getType();
            if (null != type && type == 1){
                return true;
            }
        }
        return false;
    }

    /**
     * 获取分页活动评论列表
     * @param request
     * @return
     */
    @Override
    public APIResponse<PageObj<List<RespActivityComment>>> getPageActivityComments(ReqActivity request) {
        //评论列表
        ReqActivity commentRequest = new ReqActivity();
        commentRequest.setPageNo(request.getPageNo());
        if (null == request.getPageSize()){
            request.setPageSize(OutdoorConstants.PAGE_COMMENT_NUM);
        }
        commentRequest.setPageSize(request.getPageSize());
        commentRequest.setActivityId(request.getActivityId());
        return APIResponse.returnSuccess(getActivityCommentList(commentRequest));
    }


    /**
     * 获取活动评论列表
     * @param request
     * @return
     */
    public PageObj<List<RespActivityComment>> getActivityCommentList(ReqActivity request) {

        PageObj<List<RespComment>>  listPageObj = getCommentPage(request);
        if (null == listPageObj){
            return null;
        }
        PageObj<List<RespActivityComment>> pageObj = new PageObj<>();
        pageObj.setPageCount(listPageObj.getPageCount());
        pageObj.setPageNum(listPageObj.getPageNum());
        pageObj.setSize(listPageObj.getSize());
        pageObj.setTotal(listPageObj.getTotal());
        pageObj.setItems(getComments(listPageObj.getItems()));
        return pageObj;
    }

    /**
     * 从dubbo中取出分页评论对象
     * @param request
     * @return
     */
    private PageObj<List<RespComment>> getCommentPage(ReqActivity request){
        ReqCommentQuery reqCommentQuery = new ReqCommentQuery();
        reqCommentQuery.setSystemCode(UserCenterConstants.SystemCode.SYSTEM_OUTDOOR);
        reqCommentQuery.setBusinessCode(UserCenterConstants.BusinessCode.BUSINESS_OUTDOOR_CM);
        reqCommentQuery.setBusinessId(request.getActivityId());
        reqCommentQuery.setPageNum(request.getPageNo());
        reqCommentQuery.setPageSize(request.getPageSize());
        PageObj<List<RespComment>> listPageObj = new PageObj<>();
        listPageObj.setItems(new ArrayList<RespComment>());
        try {
            listPageObj = commentServiceFacade.commentQuery(reqCommentQuery).getData();
        }catch (Exception e){
            logger.error("活动评论服务调不通！");
        }
        return listPageObj;
    }


    /**
     * 将分页中的评论列表拿出来
     * @param comments
     * @return
     */
    private List<RespActivityComment> getComments(List<RespComment> comments){
        List<RespActivityComment> commentList = new ArrayList<>();
        if (null != comments && comments.size() >0) {
            for (RespComment comment : comments) {
                RespActivityComment activityComment = new RespActivityComment();
                activityComment.setCommentId(comment.getId());
                activityComment.setCommentContent(comment.getCommentContent());
                activityComment.setCommentTime(comment.getCreateTime().getTime());
                activityComment.setScore(comment.getScore());
                Integer userId = comment.getFromUser();
                activityComment.setUserId(userId);

                RespActivityUser user = getUserById(userId);
                activityComment.setIconUrl(user.getIconUrl());
                activityComment.setUserName(user.getUserName());
                activityComment.setPlatformLevel(user.getLevel());
                commentList.add(activityComment);
            }
        }
        return commentList;
    }


    /**
     * 从dubbo中取出分页用户ID对象
     * @param request
     * @return
     */
    private PageObj<List<Integer>> getUserIdPage(ReqActivity request){
        ReqUserCollectQuery reqUserCollectQuery = new ReqUserCollectQuery();
        reqUserCollectQuery.setSystemCode(UserCenterConstants.SystemCode.SYSTEM_OUTDOOR);
        reqUserCollectQuery.setBusinessCode(UserCenterConstants.BusinessCode.BUSINESS_OUTDOOR_CM);
        reqUserCollectQuery.setBusinessId(request.getActivityId());
        reqUserCollectQuery.setPageNum(request.getPageNo());
        reqUserCollectQuery.setPageSize(request.getPageSize());
        PageObj<List<Integer>> listPageObj = new PageObj<>();
        listPageObj.setItems(new ArrayList<Integer>());
        try {
            listPageObj = userCollectServiceFacade.queryUsersByBusiness(reqUserCollectQuery).getData();
        }catch (Exception e){
            logger.error("dubbo服务：queryUsersByBusiness出错！"+e);
        }
        return listPageObj;
    }



    /**
     *
     * 通过用户id获取用户信息
     */
    private RespActivityUser getUserById(Integer uid){
        RespActivityUser user = new RespActivityUser();
        if (null != uid) {
            try {
                RespUserInfoBase respUserInfoBase = userServiceFacade.queryUserInfo(uid).getData();
                if (null != respUserInfoBase) {
                    user.setUserId(respUserInfoBase.getUid());
                    user.setLevel(respUserInfoBase.getLevel());
                    user.setIconUrl(respUserInfoBase.getIcon());
                    user.setUserName(respUserInfoBase.getNickName());
                }
            } catch (Exception e) {
                logger.error("getUserById用户信息服务调不通！");
            }
        }
        return user;
    }

    /**
     * 通过用户id批量获取用户信息
     * @param ids
     * @return
     */
    private List<RespActivityUser> getUsers(List<Integer> ids){
        List<RespActivityUser> users = new ArrayList<>();
        if (null != ids && ids.size() > 0) {
            try {
                List<RespUserInfoDetail> respUserInfoBaseList = userServiceFacade.batchQueryUserInfoDetail(ids).getData();
                //ZJ改的
                if (respUserInfoBaseList.size() > 0) {
                    for (RespUserInfoBase userInfo : respUserInfoBaseList) {
                        RespActivityUser user = new RespActivityUser();
                        user.setUserId(userInfo.getUid());
                        user.setLevel(userInfo.getLevel());
                        user.setIconUrl(userInfo.getIcon());
                        user.setUserName(userInfo.getNickName());
                        users.add(user);
                    }
                }
            } catch (Exception e) {
                logger.error("getUsers用户信息服务调不通！");
            }
        }
        return users;
    }

}
